package com.turing.post.common.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.capitalaccounts.util.BankAccountDetail;
import com.turing.post.capitalaccounts.util.BankAccountDetailDao;
import com.turing.post.cardmanagement.util.AdjustInOutStockOrderDao;
import com.turing.post.cardmanagement.util.InitialInStockOrder;
import com.turing.post.cardmanagement.util.InitialInStockOrderDao;
import com.turing.post.cardmanagement.util.MakeCardApprovalDao;
import com.turing.post.cardmanagement.util.TransferInOutStockApprovalDao;
import com.turing.post.cardmanagement.util.TransferInOutStockOrderDao;
import com.turing.post.common.util.CommonApplicationException;
import com.turing.post.common.util.CommonRespCode;
import com.turing.post.common.util.Global;
import com.turing.post.common.util.LeftMenu;
import com.turing.post.common.util.LeftParentMenu;
import com.turing.post.common.util.LogonResult;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOpMenuDao;
import com.turing.post.common.util.SysOpMenuGroup;
import com.turing.post.common.util.SysOpMenuGroupDao;
import com.turing.post.common.util.SysOpSap;
import com.turing.post.common.util.SysOpSapDao;
import com.turing.post.common.util.SysOpUser;
import com.turing.post.common.util.SysOpUserBusiness;
import com.turing.post.common.util.SysOpUserDao;
import com.turing.post.common.util.SysOpUserRole;
import com.turing.post.common.util.SysOpUserRoleDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.IssueFeePolicy;
import com.turing.post.organization.util.IssueFeePolicyDao;
import com.turing.post.organization.util.IssueFeePolicyLimitDao;
import com.turing.post.organization.util.MerchantContractDao;
import com.turing.post.organization.util.MerchantFeePolicy;
import com.turing.post.organization.util.MerchantFeePolicyDao;
import com.turing.post.organization.util.MerchantSecretPolicy;
import com.turing.post.organization.util.MerchantSecretPolicyDao;
import com.turing.post.organization.util.VoucherAdjustOrderDao;
import com.turing.post.organization.util.VoucherInStockOrderDao;
import com.turing.post.organization.util.VoucherTransferOrderDao;
import com.turing.post.salesmanage.util.DepositOrder;
import com.turing.post.salesmanage.util.DepositOrderDao;
import com.turing.post.salesmanage.util.RedempOrder;
import com.turing.post.salesmanage.util.RedempOrderDao;
import com.turing.post.salesmanage.util.SaleOrder;
import com.turing.post.salesmanage.util.SaleOrderDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;
import com.turing.post.util.SHA1;

@Stateless(mappedName = "common.impl.SysOpUserBusinessImpl")
@Remote
@Local
public class SysOpUserBusinessImpl implements SysOpUserBusiness {

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	// 菜单组
	@EJB(mappedName = "common.impl.SysOpMenuGroupDaoImpl")
	private SysOpMenuGroupDao sysOpMenuGroupDaoImpl;

	// 菜单
	@EJB(mappedName = "common.impl.SysOpMenuDaoImpl")
	private SysOpMenuDao sysOpMenuDaoImpl;

	// 用户表
	@EJB(mappedName = "common.impl.SysOpUserDaoImpl")
	private SysOpUserDao sysOpUserDaoImpl;

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;

	@EJB(mappedName = "common.impl.SysOpSapDaoImpl")
	private SysOpSapDao sysOpSapDaoImpl;

	@EJB(mappedName = "	common.impl.SysOpUserRoleDaoImpl")
	private SysOpUserRoleDao sysOpUserRoleDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.MakeCardApprovalDaoImpl")
	private MakeCardApprovalDao makeCardApprovalDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.TransferInOutStockOrderDaoImpl")
	private TransferInOutStockOrderDao transferInOutStockOrderDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.AdjustInOutStockOrderDaoImpl")
	private AdjustInOutStockOrderDao adjustInOutStockOrderDaoImpl;

	@EJB(mappedName = "organization.impl.IssueFeePolicyDaoImpl")
	private IssueFeePolicyDao issueFeePolicyDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantContractDaoImpl")
	private MerchantContractDao merchantContractDaoImpl;

	@EJB(mappedName = "organization.impl.VoucherInStockOrderDaoImpl")
	private VoucherInStockOrderDao voucherInStockOrderDaoImpl;

	@EJB(mappedName = "organization.impl.VoucherTransferOrderDaoImpl")
	private VoucherTransferOrderDao voucherTransferOrderDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.TransferInOutStockApprovalDaoImpl")
	private TransferInOutStockApprovalDao transferInOutStockApprovalDaoImpl;

	@EJB(mappedName = "organization.impl.VoucherAdjustOrderDaoImpl")
	private VoucherAdjustOrderDao voucherAdjustOrderDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.InitialInStockOrderDaoImpl")
	private InitialInStockOrderDao initialInStockOrderDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderDaoImpl")
	private DepositOrderDao depositOrderDaoImpl;

	@EJB(mappedName = "salesmanage.impl.SaleOrderDaoImpl")
	private SaleOrderDao saleOrderDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantFeePolicyDaoImpl")
	private MerchantFeePolicyDao merchantFeePolicyDaoImpl;

	@EJB(mappedName = "salesmanage.impl.RedempOrderDaoImpl")
	private RedempOrderDao redempOrderDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantSecretPolicyDaoImpl")
	private MerchantSecretPolicyDao merchantSecretPolicyDaoImpl;

	@EJB(mappedName = "organization.impl.IssueFeePolicyLimitDaoImpl")
	private IssueFeePolicyLimitDao issueFeePolicyLimitDaoImpl;

	@EJB(mappedName = "capitalaccounts.impl.BankAccountDetailDaoImpl")
	private BankAccountDetailDao bankAccountDetailDaoImpl;

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	private void errException(String error) throws PCPSApplicationException {
		throw new CommonApplicationException(
				CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
				CommonRespCode.USERLOGON, error);
	}

	@Override
	public SysOpUser sysOpUserLogon(PCPSWebInput webInput, SysOpUser sysOpUser)
			throws PCPSApplicationException {
		String errorMsg = "";
		if (sysOpUser == null) {
			errException("用户登录输入对象为空!");
		}
		// 根据用户名查
		SysOpUser eo = sysOpUserDaoImpl.getSysOpUserByOperLogonName(sysOpUser
				.getOperLogonName());
		if (eo == null) {
			// 用户名不存在
			eo = new SysOpUser();
			errException("用户名输入错误!");
		} else {
			// 互联网web日志记录员
			if (eo.getInternetAgent().equals(SysOpUser.Internet_Agent)) {
				errException("用户不为登录用户，禁止登录!");
			}
			if (eo.getStatus().equals(SysOpUser.Status_Stop)) {
				errException("用户已停用，禁止登录!");
			}
			// 全局字典
			Global global = commonDaoImpl.getGlobalInfo();
			// MaxPwdErrCnt>0限制错误次数，为0不限制
			if (global.getMaxPwdErrCnt() > 0) {
				// 已经超过最大错误次数
				if (eo.getPwdErrCnt().compareTo(global.getMaxPwdErrCnt()) >= 0) {
					// 判断是否在global登录限制时间之内，限制时间分钟
					long limit = (commonDaoImpl.getDatabaseSysTime().getTime() - eo
							.getLastPwdErrTime().getTime()) / 60000;
					if (limit < global.getPwdErrLimit()) {
						errException("密码错误次数超过限制，锁定" + global.getPwdErrLimit()
								+ "分钟!");
					}
				}
			}
			String inputoperPasswd = new SHA1()
					.getDigestOfString((sysOpUser.getOperLogonName() + sysOpUser
							.getOperPasswd()).getBytes());
			// 判断密码
			if (!eo.getOperPasswd().equals(inputoperPasswd)) {
				// 记录密码错误时间和次数
				eo.setPwdErrCnt(eo.getPwdErrCnt() + 1);
				eo.setLastPwdErrTime(commonDaoImpl.getDatabaseSysTime());
				sysOpUserDaoImpl.updateSysOpUserInfo(eo);
				errorMsg = "密码输入错误";
				// errException("密码输入错误!");
			} else {
				// 登录成功修改密码错误次数
				if (eo.getPwdErrCnt().compareTo(0) > 0) {
					eo.setPwdErrCnt(0);
					sysOpUserDaoImpl.updateSysOpUserInfo(eo);
				}
				// 判断发卡商状态
				if (!PCPSUtil.isEmpty(eo.getOperBranchNo())) {
					String issueCompanyNo = eo.getOperBranchNo()
							.substring(0, 6);
					IssueCompany ic = issueCompanyDaoImpl
							.getIssueCompanyByIssueCompanyNo(issueCompanyNo);
					if (ic != null) {
						if (ic
								.getActivate()
								.equals(
										IssueCompany.ISSUECOMPANY_ACTIVATE_NOTACTIVATED)) {
							errException("该用户归属发卡商未激活，无法登录!");
						}
						if (ic.getCategory().equals(
								IssueCompany.ISSUECOMPANY_CATEGORY_LEASE)) {
							if (ic.getLeaseExpired() == null) {
								errException("该用户归属发卡商未设置有效期!");
							} else {
								if (ic.getLeaseExpired().before(
										commonDaoImpl.getSysDateFormatYMD())) {
									errException("该用户归属发卡商已过平台租用期!");
								}
							}
						}
					}
				}
			}
		}
		// 错误返回值
		eo.setErrorMsg(errorMsg);
		return eo;
	}

	@Override
	public LogonResult insertSysOperLog(PCPSWebInput webInput,
			SysOpUser sysOpUser) throws PCPSApplicationException {
		if (!"用户名输入错误!".equals(sysOpUser.getErrorMsg())) {
			// 插入数据库日志
			SysOperLog sysOperLog = new SysOperLog();
			sysOperLog.setOperId(sysOpUser.getOperId());
			sysOperLog.setOperType(SysOperLog.operType_Logon);
			sysOperLog.setLogName("用户登录");
			if (webInput != null) {
				webInput.setOperBranchNo(sysOpUser.getOperBranchNo());
				sysOperLog.setIpAddress(webInput.getIpAddress());
				if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
					sysOperLog.setIssueCompanyNo(webInput.getOperBranchNo()
							.substring(0, 6));
					sysOperLog.setBranchNo(webInput.getOperBranchNo());
				}
			}
			sysOperLog.setRemark("用户" + sysOpUser.getOperLogonName() + "登录 "
					+ sysOpUser.getErrorMsg());
			sysOperLogDaoImpl.insertSysOperLog(sysOperLog);
		}
		if ("密码输入错误".equals(sysOpUser.getErrorMsg())) {
			return new LogonResult(PCPSUtil.FAILED, "", sysOpUser.getErrorMsg()
					+ ",已错误" + sysOpUser.getPwdErrCnt() + "次");
		} else {
			return new LogonResult(PCPSUtil.FAILED, "", sysOpUser.getErrorMsg());
		}
	}

	@Override
	public List<SysOpMenuGroup> getLogonSysOpMenuGroup(SysOpUser eo) {
		// 返回菜单列表值
		List<SysOpMenuGroup> returnList = new ArrayList<SysOpMenuGroup>();
		List<SysOpUserRole> roleList = sysOpUserRoleDaoImpl
				.getSysOpUserRoleByOperId(eo.getOperId());
		if (roleList == null || roleList.size() < 1) {
			return null;
		}
		String roleIds = getRoleIds(roleList);
		// 根据用户角色查询用户可以拥有的所有了服务,只查询一次
		List<LeftMenu> leftMenuList = sysOpMenuDaoImpl
				.getSysOpMenuListByRoleId(roleIds);
		// 查询该用户能够得到的菜单组,循环菜单组
		SysOpMenuGroup sysOpMenuGroup = null;
		List<SysOpMenuGroup> sysOpMenuGroupList = sysOpMenuGroupDaoImpl
				.getSysOpMenuGroupListByRoleId(roleIds);
		for (int i = 0; i < sysOpMenuGroupList.size(); i++) {
			// 子系统类别
			sysOpMenuGroup = sysOpMenuGroupList.get(i);
			// 父节点
			List<LeftParentMenu> leftParentMenuList = sysOpMenuDaoImpl
					.getSysOpMenuListByRoleIdAndMenuGrpId(roleIds,
							sysOpMenuGroup.getMenuGrpId());
			// 为父节点添加子节点
			leftParentMenuList = addChildren(leftParentMenuList, leftMenuList);
			sysOpMenuGroup.setLeftParentMenu(leftParentMenuList);
			returnList.add(sysOpMenuGroup);// 返回菜单目录
		}
		return returnList;
	}

	private String getRoleIds(List<SysOpUserRole> roleList) {
		String result = "";
		for (int i = 0; i < roleList.size(); i++) {
			result += roleList.get(i).getRoleId() + ",";
		}
		return result.substring(0, result.length() - 1);
	}

	private List<LeftParentMenu> addChildren(
			List<LeftParentMenu> leftParentMenuList, List<LeftMenu> leftMenuList) {
		LeftParentMenu leftParent = null;
		LeftParentMenu leftParentMenu = null;
		// 父节点
		List<LeftParentMenu> returnList = new ArrayList<LeftParentMenu>();
		for (int i = 0; i < leftParentMenuList.size(); i++) {
			leftParent = leftParentMenuList.get(i);
			leftParentMenu = new LeftParentMenu();
			leftParentMenu.setMenuId(leftParent.getMenuId());
			leftParentMenu.setMenuName(leftParent.getMenuName());
			leftParentMenu.setLeftMenuList(addLastChildren(leftParentMenu
					.getMenuId(), leftMenuList));
			returnList.add(leftParentMenu);
		}
		return returnList;
	}

	@SuppressWarnings("unchecked")
	private List<LeftMenu> addLastChildren(Integer menuId,
			List<LeftMenu> leftMenuList) {
		List<LeftMenu> resultList = new ArrayList<LeftMenu>();
		LeftMenu leftMenu = null;
		for (int i = 0; i < leftMenuList.size(); i++) {
			leftMenu = leftMenuList.get(i);
			if (menuId.equals(leftMenu.getSuperMenuId())) {
				resultList.add(leftMenu);
			}
		}
		return resultList;
	}

	@Override
	public void insertSysOpUser(PCPSWebInput webInput, SysOpUser sysOpUser)
			throws PCPSApplicationException {
		if (sysOpUser.getOperLogonName().trim().length() < 6) {
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "用户名长度不能小于6位!");
		}
		// 根据用户名查询
		SysOpUser eo = sysOpUserDaoImpl.getSysOpUserByOperLogonName(sysOpUser
				.getOperLogonName());
		if (eo != null) {
			// 用户名存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "该用户名已经存在!");
		}

		String userPasswd = new SHA1().getDigestOfString((sysOpUser
				.getOperLogonName() + sysOpUser.getOperLogonName()).getBytes());
		// 密文密码
		String operPasswd = new SHA1().getDigestOfString((sysOpUser
				.getOperLogonName() + sysOpUser.getOperPasswd()).getBytes());
		if (userPasswd.equals(operPasswd)) {
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "用户名和密码重复!");
		}
		BigInteger id = sysOpUserDaoImpl.getMaxOperId();
		sysOpUser.setOperId(id);
		sysOpUser.setOperPasswd(operPasswd);
		sysOpUser.setInternetAgent("0");
		sysOpUser.setPwdErrCnt(0);
		sysOpUser.setLastPwdChangeTime(commonDaoImpl.getDatabaseSysTime());
		sysOpUserDaoImpl.insertSysOpUserInfo(sysOpUser);
		if (sysOpUser.getRoleId().compareTo(BigInteger.ZERO) != 0) {
			if (PCPSUtil.isEmpty(sysOpUser.getRoles())) {
				throw new CommonApplicationException(
						CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
						CommonRespCode.EDIT_SYSOPUSER, "用户未选择角色!");
			}
			String[] roles = sysOpUser.getRoles().split("#");
			SysOpUserRole sour = null;
			for (int i = 0; i < roles.length; i++) {
				sour = new SysOpUserRole();
				sour.setOperId(id);
				sour.setRoleId(new BigInteger(roles[i]));
				sysOpUserRoleDaoImpl.insertSysOpUserRole(sour);
			}
		}
		// 插入日志数据
		insertRecordingOperationLog(webInput, "创建用户信息", sysOpUser,
				SysOperLog.operType_Add, "Answer3");
	}

	@Override
	public void updateSysOpUser(PCPSWebInput webInput, SysOpUser sysOpUser,
			BigInteger roleId) throws PCPSApplicationException {
		// 根据用户名查询
		SysOpUser _sysOpUser = sysOpUserDaoImpl.getSysOpUserByOperId(sysOpUser
				.getOperId());
		if (_sysOpUser == null) {
			// 用户不存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "修改用户不存在!");
		}
		// 角色为-1标示赋权操作
		if (sysOpUser.getRoleId().compareTo(BigInteger.valueOf(-1)) == 0) {
			sysOpUserRoleDaoImpl.deleteSysOpUserRole(_sysOpUser.getOperId());
			if (!PCPSUtil.isEmpty(sysOpUser.getRoles())) {
				String[] roles = sysOpUser.getRoles().split("#");
				SysOpUserRole sour = null;
				for (int i = 0; i < roles.length; i++) {
					sour = new SysOpUserRole();
					sour.setOperId(_sysOpUser.getOperId());
					sour.setRoleId(new BigInteger(roles[i]));
					sysOpUserRoleDaoImpl.insertSysOpUserRole(sour);
				}
			}
		} else {
			// 普通修改
			_sysOpUser.setName(sysOpUser.getName());
			_sysOpUser.setSex(sysOpUser.getSex());
			_sysOpUser.setStatus(sysOpUser.getStatus());
			_sysOpUser.setLinkTele(sysOpUser.getLinkTele());
			_sysOpUser.setEmail(sysOpUser.getEmail());
			// 修改
			sysOpUserDaoImpl.updateSysOpUserInfo(_sysOpUser);
			// 插入日志数据
			insertRecordingOperationLog(webInput, "用户信息修改", sysOpUser,
					SysOperLog.operType_Edit, "Answer3");
		}
	}

	@Override
	public void updateSysOpUserQuestion(PCPSWebInput webInput,
			SysOpUser sysOpUser) throws PCPSApplicationException {
		// 根据用户名查询
		SysOpUser _sysOpUser = sysOpUserDaoImpl.getSysOpUserByOperId(sysOpUser
				.getOperId());
		if (_sysOpUser == null) {
			// 用户不存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "修改用户不存在!");
		}
		_sysOpUser.setLogonMessage(sysOpUser.getLogonMessage());
		_sysOpUser.setQuestion1(sysOpUser.getQuestion1());
		_sysOpUser.setAnswer1(sysOpUser.getAnswer1());
		_sysOpUser.setQuestion2(sysOpUser.getQuestion2());
		_sysOpUser.setAnswer2(sysOpUser.getAnswer2());
		_sysOpUser.setQuestion3(sysOpUser.getQuestion3());
		_sysOpUser.setAnswer3(sysOpUser.getAnswer3());
		sysOpUserDaoImpl.updateSysOpUserInfo(_sysOpUser);
		// 插入日志数据
		insertRecordingOperationLog(webInput, "用户信息修改", sysOpUser,
				SysOperLog.operType_Edit, "Answer3");
	}

	@Override
	public void updateSysOpUserPassword(PCPSWebInput webInput,
			String oldPassword, SysOpUser sysOpUser)
			throws PCPSApplicationException {
		SysOpUser _sysOpUser = sysOpUserDaoImpl.getSysOpUserByOperId(sysOpUser
				.getOperId());
		if (_sysOpUser == null) {
			// 用户不存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "修改用户不存在!");
		}
		String oldEncryPassword = new SHA1().getDigestOfString((sysOpUser
				.getOperLogonName() + oldPassword).getBytes());
		if (!_sysOpUser.getOperPasswd().equals(oldEncryPassword)) {
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "原始密码输入错误!");
		}
		String newoperPasswd = new SHA1().getDigestOfString((sysOpUser
				.getOperLogonName() + sysOpUser.getOperPasswd()).getBytes());
		if (_sysOpUser.getOperPasswd().equals(newoperPasswd)) {
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "原始密码不能和新密码一样!");
		}
		_sysOpUser.setOperPasswd(newoperPasswd);
		_sysOpUser.setPwdErrCnt(0);
		_sysOpUser.setLastPwdChangeTime(commonDaoImpl.getDatabaseSysTime());
		// 修改
		sysOpUserDaoImpl.updateSysOpUserInfo(_sysOpUser);
		// 插入日志数据
		insertRecordingOperationLog(webInput, "用户修改密码", sysOpUser,
				SysOperLog.operType_ChangePWD, "Answer3");
	}

	@Override
	public String resetSysOpUserPassword(PCPSWebInput webInput,
			SysOpUser sysOpUser) throws PCPSApplicationException {
		if (PCPSUtil.isEmpty(sysOpUser.getOperLogonName())) {
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "输入用户名为空!");
		}
		SysOpUser _sysOpUser = sysOpUserDaoImpl
				.getSysOpUserByOperLogonName(sysOpUser.getOperLogonName()
						.trim());
		if (_sysOpUser == null) {
			// 用户不存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "用户名不存在!");
		}
		String password = PCPSUtil.getRandomString(8);
		String newPassword = new SHA1().getDigestOfString((sysOpUser
				.getOperLogonName() + password).getBytes());
		_sysOpUser.setOperPasswd(newPassword);
		_sysOpUser.setPwdErrCnt(0);
		_sysOpUser.setLastPwdChangeTime(commonDaoImpl.getDatabaseSysTime());
		// 修改
		sysOpUserDaoImpl.updateSysOpUserInfo(_sysOpUser);
		sysOpUser.setOperPasswd(newPassword);
		// 插入日志数据
		insertRecordingOperationLog(webInput, "用户重置密码", sysOpUser,
				SysOperLog.operType_ChangePWD, "Answer3");
		// _sysOpUser.setOperPasswd(password);
		return password;
	}

	@Override
	public void getLossPasswordBySysOpUser(PCPSWebInput webInput,
			SysOpUser sysOpUser) throws PCPSApplicationException {
		SysOpUser _sysOpUser = sysOpUserDaoImpl
				.getSysOpUserByOperLogonName(sysOpUser.getOperLogonName());
		if (_sysOpUser == null) {
			// 用户不存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "用户名不存在!");
		}
		boolean isanswer = false;
		// 判断安全问题答案是否正确
		if (!PCPSUtil.isEmpty(sysOpUser.getAnswer1())) {
			isanswer = true;
		}
		if (!PCPSUtil.isEmpty(sysOpUser.getAnswer2())) {
			isanswer = true;
		}
		if (!PCPSUtil.isEmpty(sysOpUser.getAnswer3())) {
			isanswer = true;
		}
		if (!isanswer) {
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "所有安全问题答案都为空!");
		}
		// 有一个答案正确时找回密码
		if (_sysOpUser.getAnswer1().equals(sysOpUser.getAnswer1())
				|| _sysOpUser.getAnswer2().equals(sysOpUser.getAnswer2())
				|| _sysOpUser.getAnswer3().equals(sysOpUser.getAnswer3())) {
			// 密码赋值
			String newoperPasswd = new SHA1()
					.getDigestOfString((sysOpUser.getOperLogonName() + sysOpUser
							.getOperPasswd()).getBytes());
			_sysOpUser.setOperPasswd(newoperPasswd);
			_sysOpUser.setPwdErrCnt(0);
			_sysOpUser.setLastPwdChangeTime(commonDaoImpl.getDatabaseSysTime());
			// 修改
			sysOpUserDaoImpl.updateSysOpUserInfo(_sysOpUser);
			// 插入日志数据
			insertRecordingOperationLog(webInput, "用户找回密码", sysOpUser,
					SysOperLog.operType_ChangePWD, "Answer3");
		}
	}

	private void insertRecordingOperationLog(PCPSWebInput webInput,
			String logName, SysOpUser sysOpUser, String operType,
			String lastFieldName) throws PCPSApplicationException {
		String logRemark = PCPSUtil.RecordingOperationLog(sysOpUser,
				lastFieldName);
		if (!PCPSUtil.isEmpty(logRemark)) {
			// 插入数据库日志
			SysOperLog sysOperLog = new SysOperLog();
			if (sysOpUser != null && sysOpUser.getOperId() != null) {
				if (webInput.getOperId() != null) {
					sysOperLog.setOperId(webInput.getOperId());
				} else {
					sysOperLog.setOperId(sysOpUser.getOperId());
				}
				sysOperLog.setOperType(operType);
				sysOperLog.setLogName(logName);
				if (webInput != null) {
					sysOperLog.setIpAddress(webInput.getIpAddress());
				}
				if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
					sysOperLog.setIssueCompanyNo(webInput.getOperBranchNo()
							.substring(0, 6));
					sysOperLog.setBranchNo(webInput.getOperBranchNo());
				}
				sysOperLog.setRemark(logRemark);
				sysOperLogDaoImpl.insertSysOperLog(sysOperLog);
			}
		}
	}

	/**
	 * 用户登录后待办事项
	 * 
	 * @param webInput
	 * @return
	 * @throws PCPSApplicationException
	 */
	@Override
	public List<SysOpSap> getAgencyList(PCPSWebInput webInput) {
		if (webInput == null || webInput.getOperId() == null
				|| PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			return null;
		}
		List<SysOpUserRole> roleList = sysOpUserRoleDaoImpl
				.getSysOpUserRoleByOperId(webInput.getOperId());
		if (roleList == null || roleList.size() < 1) {
			return null;
		}
		String roleIds = getRoleIds(roleList);
		SysOpUser sou = sysOpUserDaoImpl.getSysOpUserByOperId(webInput
				.getOperId());
		// 角色为0的不显示
		if (sou.getRoleId().compareTo(BigInteger.ZERO) == 0) {
			return null;
		}

		List<SysOpSap> sapList = sysOpSapDaoImpl.getAgencySysOpSapList(roleIds);
		HashMap<String, String> map = getAgencyHashMap();

		List<SysOpSap> result = new ArrayList<SysOpSap>();
		SysOpSap _sap = null;
		SysOpSap sap = null;
		String value = null;
		BigInteger ints = BigInteger.ZERO;
		for (int i = 0; i < sapList.size(); i++) {
			sap = sapList.get(i);
			_sap = new SysOpSap();
			if("1025".equals(sap.getAgency())){
				_sap.setSapName("实物卡入库、撤销入库审核");
			}else{
				_sap.setSapName(sap.getSapName());
			}
			value = map.get(sap.getAgency());
			if (value == null)
				continue;
			ints = new BigInteger(getAgencyTotal(value, webInput).toString());
			_sap.setSapSeqNo(ints);
			_sap.setSapUrl(sap.getSapUrl().trim() + "&WaitPending=POST");
			if (ints.intValue() != 0) {
				result.add(_sap);
			}
		}
		return result;
	}

	private HashMap<String, String> getAgencyHashMap() {
		HashMap<String, String> map = new HashMap<String, String>();

		map.put("1013", "商户交易资费审批");
		map.put("1014", "发卡商资费审核");
		map.put("1015", "商户合同审批");
		map.put("1037", "无密码交易策略审核");
		map.put("1039", "资费上下限审核");

		map.put("1002", "制卡业务审核");
		map.put("1001", "制卡财务审批");
		map.put("1022", "启动制卡");
		map.put("1025", "实物卡入库审核");

		map.put("1005", "调拨单调出审批");
		map.put("1006", "调拨单接收审批");
		map.put("1019", "调拨单申请审批");
		map.put("1023", "调拨单接收");
		map.put("1008", "调整单审核");

		map.put("1016", "凭证入库单审核");
		map.put("1017", "凭证入库单撤销审核");
		map.put("1018", "凭证调拨单调出审核");
		map.put("1031", "凭证调拨单接收");
		map.put("1036", "凭证调拨单确认");
		map.put("1020", "凭证调整单审核");
		map.put("1021", "凭证调整单撤销审核");

		map.put("1041", "资金审核");

		map.put("1027", "打包销售单");
		map.put("1032", "销售单资金审核");
		map.put("1033", "销售单卡审核");
		map.put("1026", "激活销售单");

		map.put("1034", "打包充值单");
		map.put("1035", "充值单资金审核");
		map.put("1009", "充值单审核");

		map.put("1040", "赎回单审核");
		map.put("1030", "赎回单确认付款");
		map.put("1029", "赎回单扣账");

		return map;
	}

	private Integer getAgencyTotal(String str, PCPSWebInput webInput) {
		String operBranchNo = webInput.getOperBranchNo();
		String issueCompanyNo = PCPSUtil.getIssueCompanyNo(webInput);
		Integer count = 0;
		if ("制卡财务审批".equals(str)) {
			count = makeCardApprovalDaoImpl
					.getMakeCardApprovalTotalByConditions(issueCompanyNo, 1,
							operBranchNo, null, null, new BigInteger("-1"),
							new BigInteger("-1"), "1");
		} else if ("制卡业务审核".equals(str)) {
			count = makeCardApprovalDaoImpl
					.getMakeCardApprovalTotalByConditions(issueCompanyNo, 1,
							operBranchNo, null, null, new BigInteger("-1"),
							new BigInteger("-1"), "0");
		} else if ("调拨单调出审批".equals(str)) {
			count = transferInOutStockOrderDaoImpl
					.getTransferInOutStockOrderCount(operBranchNo, null, null,
							null, "0");
		} else if ("调拨单接收审批".equals(str)) {
			count = transferInOutStockOrderDaoImpl
					.getTransferInOutStockOrderCount(null, operBranchNo, null,
							null, "2");
		} else if ("调整单审核".equals(str)) {
			count = adjustInOutStockOrderDaoImpl.getAdjustInOutStockOrderCount(
					1, operBranchNo, null, null, "-1", "0",
					new BigInteger("-1"), new BigInteger("-1"));
		} else if ("商户交易资费审批".equals(str)) {
			count = merchantFeePolicyDaoImpl.getMrchFeePolicyTotalByConditions(
					webInput, null, null, null, null, null,
					MerchantFeePolicy.STATUS_WAIT_AUTH).intValue();
		} else if ("发卡商资费审核".equals(str)) {
			count = issueFeePolicyDaoImpl.getIssueFeePolicyTotal(webInput, "",
					new BigInteger("-1"), new BigInteger("-1"), "",
					IssueFeePolicy.IFPolicy_Wait_Auth).intValue();
		} else if ("商户合同审批".equals(str)) {
			count = merchantContractDaoImpl
					.getMerchantContractTotalByConditions(webInput, "", "",
							null, null, "5").intValue();
		} else if ("凭证入库单审核".equals(str)) {
			webInput.setAll(true);
			count = voucherInStockOrderDaoImpl.getVoucherInStockOrderListTotal(
					webInput, "", "0", "", "").intValue();
		} else if ("凭证入库单撤销审核".equals(str)) {
			webInput.setAll(true);// 只查询自己归属机构
			count = voucherInStockOrderDaoImpl.getVoucherInStockOrderListTotal(
					webInput, "", "2", "", "").intValue();
		} else if ("凭证调拨单调出审核".equals(str)) {
			count = voucherTransferOrderDaoImpl
					.getVoucherTransferOrderListTotal(webInput, null, null,
							null);
		} else if ("调拨单申请审批".equals(str)) {
			count = transferInOutStockApprovalDaoImpl
					.getTransferInOutStockApprovalCount(webInput, operBranchNo,
							operBranchNo, new BigInteger("-1"), "", null, null);
		} else if ("凭证调整单审核".equals(str)) {
			webInput.setAll(true);// 只查询自己归属机构
			count = voucherAdjustOrderDaoImpl
					.getVoucherAdjustOrderByApplyListTotal(webInput,
							operBranchNo, "0", "", null, null).intValue();
		} else if ("凭证调整单撤销审核".equals(str)) {
			webInput.setAll(true);// 只查询自己归属机构
			count = voucherAdjustOrderDaoImpl
					.getVoucherAdjustOrderByCancelListTotal(webInput,
							operBranchNo, "0", "", null, null).intValue();
		} else if ("凭证调拨单接收".equals(str)) {
			count = voucherTransferOrderDaoImpl
					.getVoucherTransferOrderListTotalByReceive(webInput, null,
							null, null);
		} else if ("凭证调拨单确认".equals(str)) {
			count = voucherTransferOrderDaoImpl
					.getVoucherTransferOrderListTotalByConfirm(webInput, null,
							null, null);
		} else if ("启动制卡".equals(str)) {
			count = makeCardApprovalDaoImpl
					.getApprovalMakeCardTotalByConditions(webInput.getOperId(),
							operBranchNo, null, null, "2");
		} else if ("调拨单接收".equals(str)) {
			count = transferInOutStockOrderDaoImpl
					.getTransferInOutStockOrderCount("", operBranchNo, null,
							null, "1");
		} else if ("实物卡入库审核".equals(str)) {
			count = initialInStockOrderDaoImpl.getInitialInStockOrderTotal(
					webInput, null, null,
					InitialInStockOrder.InStockOrder_Status_Wait);
		} else if ("打包销售单".equals(str)) {
			count = saleOrderDaoImpl.getActivateSaleOrderList(webInput, null,
					null, null, null, null, null, null,
					SaleOrder.SALEORDER_ORDERSTATUS_LIBRARY, null, null).size();
		} else if ("销售单资金审核".equals(str)) {
			count = saleOrderDaoImpl.getActivateSaleOrderList(webInput, null,
					null, null, null, null, null, operBranchNo,
					SaleOrder.SaleOrder_OrderStatus_Sent, null, null).size();
		} else if ("销售单卡审核".equals(str)) {
			count = saleOrderDaoImpl.getActivateSaleOrderList(webInput, null,
					null, null, null, null, null, operBranchNo,
					SaleOrder.SaleOrder_OrderStatus_AuthMoney, null, null)
					.size();
		} else if ("激活销售单".equals(str)) {
			count = saleOrderDaoImpl.getActivateSaleOrderList(webInput, null,
					null, null, null, null, null, operBranchNo,
					SaleOrder.SaleOrder_OrderStatus_AuthCard, null, null)
					.size();
		} else if ("充值单审核".equals(str)) {
			webInput.setAll(false);
			count = depositOrderDaoImpl.getDepositOrderTotalByCondition(
					webInput, null, operBranchNo, null, null, null, null, null,
					DepositOrder.SaleOrder_OrderStatus_AuthMoney, null, null)
					.intValue();
		} else if ("打包充值单".equals(str)) {
			webInput.setAll(false);
			count = depositOrderDaoImpl.getDepositOrderTotalByCondition(
					webInput, null, operBranchNo, null, null, null, null, null,
					DepositOrder.DEPORDER_ORDERSTATUS_HAVEPAID, null, null)
					.intValue();
		} else if ("充值单资金审核".equals(str)) {
			webInput.setAll(false);
			count = depositOrderDaoImpl.getDepositOrderTotalByCondition(
					webInput, null, operBranchNo, null, null, null, null, null,
					DepositOrder.DEPORDER_ORDERSTATUS_Send, null, null)
					.intValue();
		} else if ("赎回单扣账".equals(str)) {
			webInput.setAll(false);
			count = redempOrderDaoImpl.getRedempOrderTotalByCondition(webInput,
					null, operBranchNo, null, null,
					RedempOrder.OrderStatus_SecPass, null).intValue();
		} else if ("赎回单确认付款".equals(str)) {
			webInput.setAll(false);
			count = redempOrderDaoImpl.getRedempOrderTotalByCondition(webInput,
					null, operBranchNo, null, null,
					RedempOrder.OrderStatus_Debit, null).intValue();
		} else if ("赎回单审核".equals(str)) {
			webInput.setAll(false);
			count = redempOrderDaoImpl.getRedempOrderTotalByCondition(webInput,
					null, operBranchNo, null, null,
					RedempOrder.OrderStatus_Confirm, null).intValue();
		} else if ("无密码交易策略审核".equals(str)) {
			count = merchantSecretPolicyDaoImpl
					.getMerchantSecretPolicyByBusinessCount(webInput, null,
							null, null,
							MerchantSecretPolicy.STATUS_WAIT_AUDITING)
					.intValue();
		} else if ("资费上下限审核".equals(str)) {
			count = issueFeePolicyLimitDaoImpl
					.getIssueFeePolicyLimitForNotEffective(webInput
							.getOperBranchNo().substring(0, 6));
		} else if ("资金审核".equals(str)) {
			webInput.setAll(false);
			count = bankAccountDetailDaoImpl.getBankAccountDetailTotalByCond(
					webInput, operBranchNo, BankAccountDetail.STATUS_NOCHECK);
		}
		return count;
	}

	@Override
	public void deleteSysOpUser(BigInteger operId)
			throws PCPSApplicationException {
		// 根据用户名查询
		SysOpUser _sysOpUser = sysOpUserDaoImpl.getSysOpUserByOperId(operId);
		if (_sysOpUser == null) {
			// 用户不存在
			throw new CommonApplicationException(
					CommonApplicationException.ERRCODE_CATEGORY_APPLICATION,
					CommonRespCode.EDIT_SYSOPUSER, "修改用户不存在!");
		}

		// 删除用户的角色关联信息
		sysOpUserRoleDaoImpl.deleteSysOpUserRole(_sysOpUser.getOperId());

		// 删除用户信息
		sysOpUserDaoImpl.deleteSysOpUser(_sysOpUser.getOperId());
	}
}
